package com.yicong.ants.manager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.constraintlayout.widget.Group;
import androidx.fragment.app.FragmentActivity;

import com.blankj.utilcode.util.PermissionUtils;
import com.cchao.simplelib.LibCore;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.king.app.updater.AppUpdater;
import com.king.app.updater.UpdateConfig;
import com.king.app.updater.callback.UpdateCallback;
import com.king.app.updater.http.OkHttpManager;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yicong.ants.BuildConfig;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.TipsDialog;
import com.yicong.ants.bean.global.VersionBean;
import com.yicong.ants.utils.AppUtils;
import com.yicong.ants.utils.L;
import com.yicong.ants.utils.PermissionsChecker;
import com.yicong.ants.utils.ToastUtils;
import com.yicong.ants.view.BasePopupWindow;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * 应用更新版本提示框
 *
 * @author cchao
 */
public class AppUpdatePopupWindow extends BasePopupWindow {

    private ProgressBar mProgressBar;
    private TextView mProgressText;
    private Group group;
    private LinearLayout buttonLayout;
    private TextView mUpdateContent, mVersion, mUpdateText;
    private VersionBean mVersionBean;
    Activity mActivity;
    DownloadManager mDownloadManager = new DownloadManager();
    public static boolean isDownloading;

    public AppUpdatePopupWindow(Activity activity, VersionBean mDatas) {
        super(activity);
        mVersionBean = mDatas;
        mActivity = activity;

        mView.findViewById(R.id.iv_exit).setVisibility(mVersionBean.getForced_update() == 1 ? View.GONE : View.VISIBLE);

        this.setFocusable(!mDatas.isForcedUpdate());
        mVersion.setText(mVersionBean.getVersion());
        mUpdateContent.setText(Html.fromHtml(mVersionBean.getExplain()));
        mDownloadManager.setListener(progress -> {
            //
            mProgressText.setText(progress + "%");
            mProgressBar.setProgress(progress);
        });
    }

    private void startDownload() {
        if (mVersionBean == null || mActivity == null) {
            return;
        }

        if (isDownloading) {
            UiHelper.showToast("正在下载中");
            return;
        }

        buttonLayout.setVisibility(View.GONE);
        group.setVisibility(View.VISIBLE);

        String fileUrl = mVersionBean.getUrl();
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        Map<String, String> map = new HashMap<>(8);
        map.put("fileUrl", fileUrl);
        map.put("filePath", AppUtils.APK_UPDATE_PATH);
        map.put("fileName", fileName);

//        mDownloadManager.download(mActivity, map);
        DownloadHelper.startDown(mActivity, fileUrl, progress -> {
            mProgressText.setText(progress + "%");
            mProgressBar.setProgress(progress);
        });
        if (mVersionBean.getForced_update() != 1) {
            mUpdateText.setText("后台静默下载更新");
        }
        isDownloading = true;
    }

    @Override
    public void initSetting() {
        this.setOutsideTouchable(false);
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void initAfterShow() {
        super.initAfterShow();
        mVersion.setText(mVersionBean.getVersion());
        mUpdateContent.setText(Html.fromHtml(mVersionBean.getExplain()));
    }

    @Override
    public void initView() {
        mView = LayoutInflater.from(mContext).inflate(R.layout.app_update_dialog, null);
        group = mView.findViewById(R.id.progress_group);
        mProgressBar = mView.findViewById(R.id.circle_progress);
        mProgressText = mView.findViewById(R.id.progress_text);
        mVersion = mView.findViewById(R.id.tv_version);
        mUpdateContent = mView.findViewById(R.id.tv_update_content);
        mUpdateText = mView.findViewById(R.id.tv_update);
        buttonLayout = mView.findViewById(R.id.button_layout);

        mView.findViewById(R.id.iv_exit).setOnClickListener(v -> {
            if (mVersionBean.getForced_update() == 1) {
                ToastUtils.showShort(mContext, "当前版本过低，请更新！");
                RxHelper.timerConsumer(1000, new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        mActivity.finish();
                        mActivity.finishAffinity();
                        System.exit(0);
                    }
                });
                return;
            }
            dismiss();
        });
        mView.findViewById(R.id.tv_update).setOnClickListener(v -> {
            if (PermissionUtils.isGranted(Constants.READ_WRITE)) {
                next();
            } else {
                TipsDialog dialog = new TipsDialog(mActivity, R.layout.dialog_tips_app);
                dialog.setTitle("温馨提示");
                dialog.setContext("需要获取读写权限将更新下载的安装文件保存在本地，才能正常更新，是否获取权限？");
                dialog.setSureListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        next();
                    }
                });
                dialog.showDialog();
            }
        });
    }

    private void next() {
        Disposable disposable = new RxPermissions((FragmentActivity) mActivity)
                .request(Constants.READ_WRITE)
                .subscribe(aBoolean -> {
                    if (!aBoolean) {
                        UiHelper.showToast("请授予写入存储文件的权限");
                        return;
                    }
                    if (!PermissionsChecker.checkInstallPermission(mContext)) {
                        return;
                    }

                    //ActionTracker.download(mVersionBean.getVersion());
                    if (isDownloading && mVersionBean.getForced_update() != 1) {
                        dismiss();
                        return;
                    }
                    startDownload();
                });
    }

    static class DownloadHelper {

        static AppUpdater mAppUpdater;

        public static void startDown(Activity activity, String mUrl, DownloadManager.OnProgressListener progressBar) {
            UpdateConfig config = new UpdateConfig();
            config.setUrl(mUrl);
            config.setInstallApk(true);
            config.setReDownload(true);
            config.setAuthority(BuildConfig.APPLICATION_ID + ".fileProvider2");
            config.setPath(AppUtils.APK_UPDATE_PATH);

            mAppUpdater = new AppUpdater(LibCore.getContext(), config)
                    .setHttpManager(OkHttpManager.getInstance())
                    .setUpdateCallback(new UpdateCallback() {

                        @Override
                        public void onDownloading(boolean isDownloading) {
                            if (isDownloading) {
                                UiHelper.showToast("已经在下载中,请勿重复下载。");
                            }
                        }

                        @Override
                        public void onStart(String url) {
                            progressBar.updateProgress(0);
                        }

                        @Override
                        public void onProgress(long progress, long total, boolean isChange) {
                            if (isChange) {
                                int currProgress = Math.round(progress * 1.0f / total * 100.0f);
                                progressBar.updateProgress(currProgress);
                            }
                        }

                        @Override
                        public void onFinish(File response) {
                            progressBar.updateProgress(100);
                            UiHelper.showToast("下载完成");
                            isDownloading = false;
                            Logs.logEvent("onFinish path", response.getAbsolutePath());
                        }

                        @Override
                        public void onError(Exception e) {
                            progressBar.updateProgress(0);
                        }

                        @Override
                        public void onCancel() {
                            progressBar.updateProgress(0);
                        }
                    });
            mAppUpdater.start();
        }

    }

    static class DownloadManager {

        private OnProgressListener listener;

        public void setListener(OnProgressListener listener) {
            this.listener = listener;
        }

        public void download(Context activity, Map<String, String> map) {
            String fileUrl = map.get("fileUrl");
            String filePath = map.get("filePath");
            String fileName = map.get("fileName");
            L.e("onStartCommand--->", fileUrl + "   " + filePath + "  " + fileName);

            HttpManager.getHttp(fileUrl, null, new FileCallBack(filePath, fileName) {
                @Override
                public void onError(Call call, Exception e, int id) {
                    L.e("Exception------->", e.getMessage());
                    isDownloading = false;
                    UiHelper.showToast("安装包下载出错，请检查网络");
                }

                @Override
                public void inProgress(float progress, long total, int id) {
                    super.inProgress(progress, total, id);
                    if (null != listener) {
                        listener.updateProgress((int) (progress * 100));
                    }
                }

                @Override
                public void onResponse(File response, int id) {
                    isDownloading = false;
                    //会根据用户的数据类型打开android系统相应的Activity。
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        intent.setDataAndType(Uri.fromFile(response), "application/vnd.android.package-archive");
                    } else {//Android7.0之后获取uri要用contentProvider
                        intent.setDataAndType(Uri.parse("file://" + response.toString()), "application/vnd.android.package-archive");
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                    //开始安装
                    activity.startActivity(intent);
                    //关闭旧版本的应用程序的进程
                    // android.os.Process.killProcess(android.os.Process.myPid());
                }
            });
        }

        public interface OnProgressListener {
            void updateProgress(int progress);
        }
    }
}
